package controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.github.pagehelper.PageInfo;

import domain.Admin;
import domain.Article;
import service.AdminService;
import service.IArticleService;

@Controller
public class LoginController {
	@Autowired
	private AdminService logser;
	@Autowired
	private IArticleService artser;

	@RequestMapping("/admin")
	public String loginView() {
		return "/admin/login";
	}

	@RequestMapping("/checklogin")
	public String checkLogin(HttpServletRequest req, String username, String password, String query) {
		Admin admin = null;
		//从session中取对象看是否存在
		Admin oldAdmin = (Admin) req.getSession().getAttribute("ADMIN_IN_SESSION");
		if (oldAdmin == null) {
			admin = logser.isExist(username, password);
		} else {
			admin = oldAdmin;
		}
		//没有登录
		if (admin == null) {
			req.setAttribute("errmsg", "请登录");
			return "admin/login";
		}else {
			req.setAttribute("errmsg", "登录成功");
		}
		//登录成功将信息存到session中
		req.getSession().setAttribute("ADMIN_IN_SESSION", admin);
		//起始页默认为1
		Integer startPage = 1;
		//每页的数目 默认为7
		Integer pageSize = 7;
		String page = req.getParameter("page");
		if (page != null) {
			Integer currentPage = Integer.valueOf(page);
			//若有则赋值
			startPage = currentPage;
		}
		//将模糊查询的信息放到请求中 由前台获取 再传到 后台防止 翻页时 丢失数据 
		//这里一开始 放在下面 然后 加了%%后面 拼在url后面就会自动解析urlEncoding。。然后就会没有数据了
		req.setAttribute("query", query);
		//将文章查询出来存到请求中  这里不能直接在listAll这里加%  判断一下吧
		if (query != null) {
			query = "%" + query + "%";
		}
		List<Article> all = artser.listAll(startPage, pageSize, query);
		PageInfo<Article> pageInfo = new PageInfo(all);
		//放在session中避免反野丢失数据 （瞎说）
		//这个是共享给jsp页面的每次都会重新查询刷新不用放在session中
		req.setAttribute("arts", all);
		req.setAttribute("pageInfo", pageInfo);
		return "admin/admin";
	}
}
